{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# -*- coding: utf-8 -*-\n",
    "from miasm.analysis.machine import Machine\n",
    "from miasm.analysis.binary import Container\n",
    "from miasm.analysis.cst_propag import propagate_cst_expr\n",
    "from miasm.analysis.data_flow import DeadRemoval, merge_blocks, remove_empty_assignblks\n",
    "from miasm.core.locationdb import LocationDB\n",
    "from future.utils import viewitems"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "filename = '../hands-on1/test-add-sub.bin'\n",
    "addr = 0x8048440"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "scrolled": false
   },
   "outputs": [],
   "source": [
    "loc_db = LocationDB()\n",
    "machine = Machine('x86_32')\n",
    "cont = Container.from_stream(open(filename, 'rb'), loc_db)\n",
    "mdis = machine.dis_engine(cont.bin_stream, loc_db=cont.loc_db)\n",
    "ir_arch = machine.ira(mdis.loc_db)\n",
    "\n",
    "asmcfg = mdis.dis_multiblock(addr)\n",
    "ircfg = ir_arch.new_ircfg_from_asmcfg(asmcfg)\n",
    "\n",
    "print('Before Simplification:')\n",
    "for lbl, irb in viewitems(ircfg.blocks):\n",
    "    print(irb)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "entry_points = set([mdis.loc_db.get_offset_location(addr)])\n",
    "init_infos = ir_arch.arch.regs.regs_init\n",
    "cst_propag_link = propagate_cst_expr(ir_arch, ircfg, addr, init_infos)\n",
    "deadrm = DeadRemoval(ir_arch)\n",
    "\n",
    "modified = True\n",
    "while modified:\n",
    "    modified = False\n",
    "    modified |= deadrm(ircfg)\n",
    "    modified |= remove_empty_assignblks(ircfg)\n",
    "\n",
    "print('After Simplification:')\n",
    "\n",
    "for lbl, irb in viewitems(ircfg.blocks):\n",
    "    print(irb)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.9"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
